// 数据分析页面的JavaScript功能

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化数据分析功能
    initDataAnalysis();
    
    // 初始化筛选功能
    initFilters();
    
    // 初始化图表
    initCharts();
    
    // 初始化表格交互
    initTableInteraction();
    
    // 添加动画效果
    addAnimationEffects();
});

// 初始化数据分析功能
function initDataAnalysis() {
    console.log('数据分析功能初始化完成');
    
    // 设置页面标题
    document.title = '数据分析 - 图书馆管理系统';
}

// 初始化筛选功能
function initFilters() {
    // 时间范围选择器
    const timeRangeSelect = document.getElementById('timeRange');
    const customDateInputs = document.querySelector('.custom-date');
    
    timeRangeSelect.addEventListener('change', function() {
        if (this.value === 'custom') {
            customDateInputs.style.display = 'flex';
        } else {
            customDateInputs.style.display = 'none';
        }
    });
    
    // 应用筛选按钮
    const applyFilterBtn = document.querySelector('.apply-filter-btn');
    applyFilterBtn.addEventListener('click', function() {
        showLoading();
        
        // 模拟数据加载
        setTimeout(() => {
            hideLoading();
            updateAllCharts();
            showToast('筛选条件已应用，数据已更新');
        }, 800);
    });
    
    // 刷新数据按钮
    const refreshBtn = document.querySelector('.refresh-btn');
    refreshBtn.addEventListener('click', function() {
        refreshData();
    });
    
    // 导出报告按钮
    const exportBtn = document.querySelector('.export-btn');
    exportBtn.addEventListener('click', function() {
        exportReport();
    });
}

// 初始化图表
function initCharts() {
    // 初始化使用率趋势图
    initUsageTrendChart();
    
    // 初始化预约时段分布图表
    initBookingTimeDistributionChart();
    
    // 初始化用户活跃度分布图表
    initUserActivityChart();
    
    // 初始化用户预约偏好图表
    initUserPreferenceChart();
    
    // 为图表控件添加事件监听器
    const chartSelects = document.querySelectorAll('.chart-time-select, .chart-type-select');
    chartSelects.forEach(select => {
        select.addEventListener('change', function() {
            const chartCard = this.closest('.chart-card');
            const chartId = chartCard.querySelector('.chart-placeholder').id;
            
            updateChart(chartId, this.name, this.value);
        });
    });
}

// 初始化使用率趋势图
function initUsageTrendChart() {
    const chartElement = document.getElementById('usageTrendChart');
    
    // 生成模拟数据
    const weeks = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
    const data = [65, 78, 72, 85, 88, 75, 62];
    
    // 渲染图表
    renderUsageTrendChart(chartElement, weeks, data);
}

// 渲染使用率趋势图
function renderUsageTrendChart(element, labels, data) {
    let html = `
        <div class="usage-trend-chart">
            <div class="chart-lines">
                <div class="chart-line"></div>
                <div class="chart-points">
    `;
    
    // 添加数据点
    data.forEach((value, index) => {
        const position = (index / (data.length - 1)) * 100;
        const height = value;
        html += `
                    <div 
                        class="chart-point" 
                        style="left: ${position}%; bottom: ${height}%"
                        title="${labels[index]}: ${value}%"
                    ></div>
        `;
    });
    
    html += `
                </div>
            </div>
            <div class="chart-grid">
    `;
    
    // 添加网格线和标签
    labels.forEach((label, index) => {
        html += `
                <div class="grid-line">${label}</div>
        `;
    });
    
    html += `
            </div>
        </div>
    `;
    
    element.innerHTML = html;
}

// 初始化预约时段分布图表
function initBookingTimeDistributionChart() {
    const chartElement = document.getElementById('bookingTimeDistributionChart');
    
    // 生成模拟数据
    const hours = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00'];
    const data = [45, 65, 30, 75, 85, 90, 60];
    
    // 渲染图表
    renderBookingDistributionChart(chartElement, hours, data);
}

// 渲染预约时段分布图表
function renderBookingDistributionChart(element, labels, data) {
    const maxValue = Math.max(...data);
    
    let html = `
        <div class="booking-distribution-chart">
            <div class="chart-bars">
    `;
    
    // 添加柱状图
    data.forEach((value, index) => {
        const height = (value / maxValue) * 100;
        html += `
                <div 
                    class="chart-bar" 
                    style="height: ${height}%"
                    title="${labels[index]}: ${value}人"
                >
                    <div class="chart-bar-value">${value}</div>
                    <div class="chart-bar-label">${labels[index]}</div>
                </div>
        `;
    });
    
    html += `
            </div>
        </div>
    `;
    
    element.innerHTML = html;
}

// 初始化用户活跃度分布图表
function initUserActivityChart() {
    const chartElement = document.getElementById('userActivityChart');
    
    // 生成模拟数据
    const activityLevels = ['高频', '中频', '低频', '偶尔', '从未使用'];
    const data = [856, 1245, 789, 456, 120];
    
    // 默认渲染柱状图
    renderUserActivityBarChart(chartElement, activityLevels, data);
}

// 渲染用户活跃度柱状图
function renderUserActivityBarChart(element, labels, data) {
    const maxValue = Math.max(...data);
    
    let html = `
        <div class="booking-distribution-chart">
            <div class="chart-bars">
    `;
    
    // 添加柱状图
    data.forEach((value, index) => {
        const height = (value / maxValue) * 100;
        const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7'];
        
        html += `
                <div 
                    class="chart-bar" 
                    style="height: ${height}%; background: linear-gradient(to top, ${colors[index]}, ${colors[index]}80)"
                    title="${labels[index]}: ${value}人"
                >
                    <div class="chart-bar-value">${value}</div>
                    <div class="chart-bar-label">${labels[index]}</div>
                </div>
        `;
    });
    
    html += `
            </div>
        </div>
    `;
    
    element.innerHTML = html;
}

// 渲染用户活跃度饼图
function renderUserActivityPieChart(element, labels, data) {
    const total = data.reduce((sum, value) => sum + value, 0);
    const colors = ['#ff6b6b', '#4ecdc4', '#45b7d1', '#96ceb4', '#ffeaa7'];
    
    let html = `
        <div class="pie-chart">
            <div class="chart-container">
                <div class="chart-slices">
    `;
    
    let startAngle = 0;
    data.forEach((value, index) => {
        const percentage = (value / total) * 100;
        const angle = (percentage / 100) * 360;
        const endAngle = startAngle + angle;
        
        // 计算扇形路径
        const largeArcFlag = angle > 180 ? 1 : 0;
        const startX = 50 + 45 * Math.cos((startAngle - 90) * Math.PI / 180);
        const startY = 50 + 45 * Math.sin((startAngle - 90) * Math.PI / 180);
        const endX = 50 + 45 * Math.cos((endAngle - 90) * Math.PI / 180);
        const endY = 50 + 45 * Math.sin((endAngle - 90) * Math.PI / 180);
        
        const pathData = `M 50 50 L ${startX} ${startY} A 45 45 0 ${largeArcFlag} 1 ${endX} ${endY} Z`;
        
        html += `
                    <div 
                        class="chart-slice" 
                        style="
                            background: ${colors[index]};
                            clip-path: path('${pathData}');
                            position: absolute;
                            width: 100%;
                            height: 100%;
                        "
                        title="${labels[index]}: ${percentage.toFixed(1)}%"
                    ></div>
        `;
        
        startAngle = endAngle;
    });
    
    html += `
                </div>
            </div>
            <div class="chart-legend">
    `;
    
    // 添加图例
    labels.forEach((label, index) => {
        const percentage = ((data[index] / total) * 100).toFixed(1);
        html += `
                <div class="legend-item">
                    <div class="legend-color" style="background: ${colors[index]}"></div>
                    <span>${label}: ${percentage}%</span>
                </div>
        `;
    });
    
    html += `
            </div>
        </div>
    `;
    
    element.innerHTML = html;
}

// 初始化用户预约偏好图表
function initUserPreferenceChart() {
    const chartElement = document.getElementById('userPreferenceChart');
    
    // 生成模拟数据
    const preferences = ['靠窗', '靠角落', '中央区域', '电源附近', '安静区'];
    const data = [450, 380, 520, 680, 320];
    
    // 默认渲染饼图
    renderUserPreferencePieChart(chartElement, preferences, data);
}

// 渲染用户预约偏好饼图
function renderUserPreferencePieChart(element, labels, data) {
    const total = data.reduce((sum, value) => sum + value, 0);
    const colors = ['#f368e0', '#ff9ff3', '#54a0ff', '#5f27cd', '#00d2d3'];
    
    let html = `
        <div class="pie-chart">
            <div class="chart-container">
                <div class="chart-slices">
    `;
    
    let startAngle = 0;
    data.forEach((value, index) => {
        const percentage = (value / total) * 100;
        const angle = (percentage / 100) * 360;
        const endAngle = startAngle + angle;
        
        // 计算扇形路径
        const largeArcFlag = angle > 180 ? 1 : 0;
        const startX = 50 + 45 * Math.cos((startAngle - 90) * Math.PI / 180);
        const startY = 50 + 45 * Math.sin((startAngle - 90) * Math.PI / 180);
        const endX = 50 + 45 * Math.cos((endAngle - 90) * Math.PI / 180);
        const endY = 50 + 45 * Math.sin((endAngle - 90) * Math.PI / 180);
        
        const pathData = `M 50 50 L ${startX} ${startY} A 45 45 0 ${largeArcFlag} 1 ${endX} ${endY} Z`;
        
        html += `
                    <div 
                        class="chart-slice" 
                        style="
                            background: ${colors[index]};
                            clip-path: path('${pathData}');
                            position: absolute;
                            width: 100%;
                            height: 100%;
                        "
                        title="${labels[index]}: ${percentage.toFixed(1)}%"
                    ></div>
        `;
        
        startAngle = endAngle;
    });
    
    html += `
                </div>
            </div>
            <div class="chart-legend">
    `;
    
    // 添加图例
    labels.forEach((label, index) => {
        const percentage = ((data[index] / total) * 100).toFixed(1);
        html += `
                <div class="legend-item">
                    <div class="legend-color" style="background: ${colors[index]}"></div>
                    <span>${label}: ${percentage}%</span>
                </div>
        `;
    });
    
    html += `
            </div>
        </div>
    `;
    
    element.innerHTML = html;
}

// 初始化表格交互
function initTableInteraction() {
    // 表格行悬停效果已通过CSS实现
    
    // 查看详情按钮事件
    const viewDetailsBtns = document.querySelectorAll('.view-details-btn');
    viewDetailsBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const tableCard = this.closest('.table-card');
            const tableTitle = tableCard.querySelector('h3').textContent;
            showToast(`查看${tableTitle}的详细数据`);
            // 实际项目中应该打开详情模态框或跳转到详情页面
        });
    });
    
    // 导出表格按钮事件
    const exportTableBtns = document.querySelectorAll('.export-table-btn');
    exportTableBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const tableCard = this.closest('.table-card');
            const tableTitle = tableCard.querySelector('h3').textContent;
            exportTableData(tableCard.querySelector('.data-table'), tableTitle);
        });
    });
    
    // 表格行点击事件
    const tableRows = document.querySelectorAll('.data-table tbody tr');
    tableRows.forEach(row => {
        row.addEventListener('click', function() {
            const firstCell = this.cells[0].textContent;
            showToast(`查看${firstCell}的详细数据`);
        });
    });
}

// 添加动画效果
function addAnimationEffects() {
    // 为指标卡片添加进入动画
    const metricCards = document.querySelectorAll('.metric-card');
    metricCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 100 + 100 * index);
    });
    
    // 为图表卡片添加进入动画
    const chartCards = document.querySelectorAll('.chart-card');
    chartCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 300 + 150 * index);
    });
    
    // 为表格卡片添加进入动画
    const tableCards = document.querySelectorAll('.table-card');
    tableCards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
        
        setTimeout(() => {
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, 600 + 150 * index);
    });
}

// 更新所有图表
function updateAllCharts() {
    // 获取当前筛选条件
    const timeRange = document.getElementById('timeRange').value;
    const dataDimension = document.getElementById('dataDimension').value;
    
    console.log('更新所有图表，时间范围：', timeRange, '数据维度：', dataDimension);
    
    // 根据时间范围和数据维度更新图表
    // 这里只是模拟，实际项目中应该根据筛选条件重新获取数据
    
    // 更新使用率趋势图
    updateUsageTrendChart(timeRange);
    
    // 更新预约时段分布图表
    updateBookingTimeDistributionChart(timeRange);
    
    // 更新用户活跃度分布图表
    updateUserActivityChart(timeRange, dataDimension);
    
    // 更新用户预约偏好图表
    updateUserPreferenceChart(dataDimension);
}

// 更新使用率趋势图
function updateUsageTrendChart(timeRange) {
    const chartElement = document.getElementById('usageTrendChart');
    let labels, data;
    
    // 根据时间范围生成不同的数据
    switch(timeRange) {
        case 'week':
            labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            data = [65, 78, 72, 85, 88, 75, 62];
            break;
        case 'month':
            labels = ['第1周', '第2周', '第3周', '第4周'];
            data = [72, 78, 82, 85];
            break;
        case 'quarter':
            labels = ['1月', '2月', '3月'];
            data = [68, 75, 80];
            break;
        case 'year':
            labels = ['Q1', 'Q2', 'Q3', 'Q4'];
            data = [70, 75, 80, 85];
            break;
        default:
            labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
            data = [65, 78, 72, 85, 88, 75, 62];
    }
    
    // 渲染图表
    renderUsageTrendChart(chartElement, labels, data);
}

// 更新预约时段分布图表
function updateBookingTimeDistributionChart(timeRange) {
    const chartElement = document.getElementById('bookingTimeDistributionChart');
    let labels, data;
    
    // 根据时间范围生成不同的数据
    switch(timeRange) {
        case 'week':
            labels = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00'];
            data = [45, 65, 30, 75, 85, 90, 60];
            break;
        case 'month':
            labels = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00'];
            data = [48, 68, 32, 78, 88, 92, 62];
            break;
        case 'quarter':
            labels = ['上午', '中午', '下午', '晚上'];
            data = [150, 80, 220, 180];
            break;
        case 'year':
            labels = ['上午', '中午', '下午', '晚上'];
            data = [160, 85, 230, 190];
            break;
        default:
            labels = ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00'];
            data = [45, 65, 30, 75, 85, 90, 60];
    }
    
    // 渲染图表
    renderBookingDistributionChart(chartElement, labels, data);
}

// 更新用户活跃度分布图表
function updateUserActivityChart(timeRange, dataDimension) {
    const chartElement = document.getElementById('userActivityChart');
    const chartType = chartElement.closest('.chart-card').querySelector('.chart-type-select').value;
    
    let labels, data;
    
    // 根据时间范围和数据维度生成不同的数据
    if (dataDimension === 'users' || dataDimension === 'all') {
        switch(timeRange) {
            case 'week':
                labels = ['高频', '中频', '低频', '偶尔', '从未使用'];
                data = [456, 890, 543, 321, 120];
                break;
            case 'month':
                labels = ['高频', '中频', '低频', '偶尔', '从未使用'];
                data = [856, 1245, 789, 456, 120];
                break;
            case 'quarter':
                labels = ['高频', '中频', '低频', '偶尔', '从未使用'];
                data = [1234, 2134, 1543, 890, 345];
                break;
            case 'year':
                labels = ['高频', '中频', '低频', '偶尔', '从未使用'];
                data = [2345, 3456, 2134, 1234, 678];
                break;
            default:
                labels = ['高频', '中频', '低频', '偶尔', '从未使用'];
                data = [856, 1245, 789, 456, 120];
        }
    } else {
        // 非用户维度时显示简化数据
        labels = ['活跃', '不活跃'];
        data = [2400, 1200];
    }
    
    // 根据图表类型渲染
    if (chartType === 'bar') {
        renderUserActivityBarChart(chartElement, labels, data);
    } else {
        renderUserActivityPieChart(chartElement, labels, data);
    }
}

// 更新用户预约偏好图表
function updateUserPreferenceChart(dataDimension) {
    const chartElement = document.getElementById('userPreferenceChart');
    const chartType = chartElement.closest('.chart-card').querySelector('.chart-type-select').value;
    
    let labels, data;
    
    // 根据数据维度生成不同的数据
    if (dataDimension === 'bookings' || dataDimension === 'all') {
        labels = ['靠窗', '靠角落', '中央区域', '电源附近', '安静区'];
        data = [450, 380, 520, 680, 320];
    } else {
        // 非预约维度时显示简化数据
        labels = ['热门区域', '一般区域', '冷门区域'];
        data = [1200, 800, 400];
    }
    
    // 渲染饼图
    renderUserPreferencePieChart(chartElement, labels, data);
}

// 更新单个图表
function updateChart(chartId, parameter, value) {
    showLoading();
    
    // 模拟加载过程
    setTimeout(() => {
        hideLoading();
        
        switch(chartId) {
            case 'usageTrendChart':
                updateUsageTrendChart(value);
                break;
            case 'bookingTimeDistributionChart':
                updateBookingTimeDistributionChart(value);
                break;
            case 'userActivityChart':
                if (parameter === 'chart-type-select') {
                    const chartElement = document.getElementById(chartId);
                    const timeRange = document.getElementById('timeRange').value;
                    const dataDimension = document.getElementById('dataDimension').value;
                    
                    // 重新获取数据并根据类型渲染
                    updateUserActivityChart(timeRange, dataDimension);
                }
                break;
            case 'userPreferenceChart':
                if (parameter === 'chart-type-select') {
                    const dataDimension = document.getElementById('dataDimension').value;
                    updateUserPreferenceChart(dataDimension);
                }
                break;
        }
        
        showToast(`图表已更新`);
    }, 500);
}

// 刷新数据
function refreshData() {
    showLoading();
    
    // 模拟数据刷新
    setTimeout(() => {
        hideLoading();
        updateAllCharts();
        showToast('数据已刷新');
    }, 1000);
}

// 导出报告
function exportReport() {
    showLoading();
    
    // 模拟导出过程
    setTimeout(() => {
        hideLoading();
        showToast('数据分析报告导出成功');
        
        // 实际项目中这里应该生成并下载报告文件
        console.log('导出数据分析报告');
    }, 1500);
}

// 导出表格数据
function exportTableData(table, title) {
    showLoading();
    
    // 模拟导出过程
    setTimeout(() => {
        hideLoading();
        showToast(`${title}数据导出成功`);
        
        // 实际项目中这里应该生成并下载CSV或Excel文件
        console.log('导出表格数据:', title);
    }, 800);
}

// 显示加载动画
function showLoading() {
    // 检查是否已经存在加载元素
    let loadingOverlay = document.querySelector('.loading-overlay');
    
    if (!loadingOverlay) {
        loadingOverlay = document.createElement('div');
        loadingOverlay.className = 'loading-overlay';
        loadingOverlay.innerHTML = `
            <div class="loading-spinner">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
        `;
        document.body.appendChild(loadingOverlay);
    }
    
    loadingOverlay.style.display = 'flex';
}

// 隐藏加载动画
function hideLoading() {
    const loadingOverlay = document.querySelector('.loading-overlay');
    if (loadingOverlay) {
        loadingOverlay.style.display = 'none';
    }
}

// 显示提示消息
function showToast(message) {
    // 检查是否已经存在toast元素
    let toast = document.querySelector('.toast');
    
    if (!toast) {
        toast = document.createElement('div');
        toast.className = 'toast';
        document.body.appendChild(toast);
    }
    
    // 设置消息内容
    toast.textContent = message;
    
    // 显示toast
    toast.classList.add('show');
    
    // 3秒后自动隐藏
    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 键盘快捷键支持
document.addEventListener('keydown', function(e) {
    // Ctrl+R 刷新数据
    if (e.ctrlKey && e.key === 'r') {
        e.preventDefault();
        refreshData();
    }
    
    // Ctrl+E 导出报告
    if (e.ctrlKey && e.key === 'e') {
        e.preventDefault();
        exportReport();
    }
});

// 响应式布局调整
window.addEventListener('resize', function() {
    // 重新渲染图表以适应新的容器大小
    updateAllCharts();
});

// 模拟实时数据更新
function simulateRealTimeUpdates() {
    setInterval(() => {
        // 随机选择一个图表进行小幅度更新
        const chartIds = ['usageTrendChart', 'bookingTimeDistributionChart', 'userActivityChart', 'userPreferenceChart'];
        const randomChartId = chartIds[Math.floor(Math.random() * chartIds.length)];
        
        // 只在非交互状态下更新
        if (!document.querySelector('.loading-overlay').style.display === 'flex') {
            updateChart(randomChartId, 'refresh', 'auto');
        }
    }, 30000); // 每30秒模拟一次数据更新
}

// 启动实时数据更新模拟
simulateRealTimeUpdates();

// 提供API: 可以被其他脚本调用的公共方法
export const DataAnalysis = {
    refreshData: refreshData,
    exportReport: exportReport,
    applyFilters: function() {
        const applyFilterBtn = document.querySelector('.apply-filter-btn');
        applyFilterBtn.click();
    },
    getCurrentFilters: function() {
        return {
            timeRange: document.getElementById('timeRange').value,
            dataDimension: document.getElementById('dataDimension').value,
            startDate: document.getElementById('startDate').value,
            endDate: document.getElementById('endDate').value
        };
    }
};